package com.jt.controller;

import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.dubbo.config.annotation.Reference;
import com.jt.pojo.Cart;
import com.jt.service.DubboCartService;
import com.jt.util.UserThreadLocal;
import com.jt.vo.SysResult;

@Controller
@RequestMapping("/cart")
public class CartController {
	@Reference(timeout = 3000,check = false)//check = false表示启动消费者的时候不检查提供者是否启动，等到用的时候再检查
	private DubboCartService dubboCartService;
	/**
	 * 1.实现购物车列表展现
	 * url http://www.jt.com/cart/show.html
	 */
	@RequestMapping("/show")
	public String show(Model model) {
		Long userId=UserThreadLocal.get().getId();//从本地线程中获取用户登录信息
		List<Cart> cartList=dubboCartService.findCartListByUserId(userId);
		model.addAttribute("cartList", cartList);
		return "cart";
	}
	
	/**
	 * 2.实现购物车商品数量修改
	 * url http://www.jt.com/cart/update/num/562379/8
	 */
	@RequestMapping("/update/num/{itemId}/{num}")
	@ResponseBody
	//public SysResult updateNum(@PathVariable Long itemId,@PathVariable Integer num) {}
	//规则:如果{参数}的名称与对象中的属性一致.则可以使用对象直接取值.
	public SysResult updateNum(Cart cart) {
		Long userId=UserThreadLocal.get().getId();
		cart.setUserId(userId);
		dubboCartService.updateNum(cart);
		return SysResult.success();
	}
	
	/**
	 * 3.删除购物车记录，并重定向到购物车页面
	 * url http://www.jt.com/cart/delete/562379.html
	 */
	
	@RequestMapping("/delete/{itemId}")
	public String deleteCart(Cart cart) {
		Long userId=UserThreadLocal.get().getId();
		cart.setUserId(userId);
		dubboCartService.deleteCart(cart);
		return "redirect:/cart/show.html";//重定向到controller
	}
	
	/**
	 * 4.实现购物车新增
	 * url http://www.jt.com/cart/add/1474391977.html
	 */
	@RequestMapping("/add/{itemId}")
	public String saveCart(Cart cart) {
		Long userId=UserThreadLocal.get().getId();
		cart.setUserId(userId);
		dubboCartService.insertCart(cart);
		return "redirect:/cart/show.html";
	}
	
}
